package com.fubukiss.rikky;

import com.easyaop.api.Arounds;
import com.easyaop.api.Events;
import com.easyaop.api.pointcut.MethodPointcut;
import com.easyaop.asm.Driver;
import com.easyaop.commons.MyLoader;
import com.easyaop.core.AroundsImpl;
import com.easyaop.core.EventsImpl;
import org.junit.Test;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.util.ASMifier;
import org.objectweb.asm.util.TraceClassVisitor;
import test2.AsmDump;

import java.io.*;
import java.nio.file.Files;

public class test {
    String className = "com.fubukiss.rikky.Mybean";
    String name=className.replaceAll("\\.","/");
    @Test
    public void 报错() throws Exception {
        Class.forName(Driver.class.getName());
        Arounds arounds = AroundsImpl.getInstance();
        MethodPointcut pointcut = MethodPointcut.of(
                className,"*","(..)"
        );
        arounds.add(pointcut, new dsfaround());
        Mybean s= null;
        try {
            s = new Mybean();
        } catch (Throwable e) {

            s = new Mybean();
            throw new RuntimeException(e);
        }
        Object o = s.test1();
    }

    @Test
    public  void loader并执行() throws Exception {


        MyLoader myLoader = new MyLoader(test.class.getClassLoader().getParent());

        File file =new File("dump/"+name+"_0.class");
        byte[] bytes = Files.readAllBytes(file.toPath());
//        byte[] bytes= MybeanDump.dump();
        Class<?> aClass = myLoader.loadClass(className, bytes);
        aClass.newInstance();
        aClass.getDeclaredMethods();

    }

    @Test
    public void dumpclass() throws Exception {

        String fileName11 = "../dump/"+name+"_0.class";
        String fileName = "src/test/java/asm/"+name+"Dump.java";

        File file = new File(fileName);
        file.getParentFile().mkdirs();
        System.out.println(file);
        OutputStream os = new FileOutputStream(fileName);

//        InputStream is = AsmDump.class.getResourceAsStream("/"+name+".class");
        InputStream is =new File(fileName11).toURI().toURL().openStream();
        ClassReader classReader = new ClassReader(is);
        ClassVisitor classVisitor = new TraceClassVisitor(null, new ASMifier()
                , new PrintWriter(os)
//                ,new PrintWriter(System.out)
        );
        classReader.accept(classVisitor
                ,0
//                , ClassReader.SKIP_FRAMES
        );
    }

}
